import { defineStore } from "pinia";
import { ref, type Ref } from "vue";
import type { TagView } from "@/typings/tag-view";
import { useRouter } from "vue-router";
import { useDesignStore } from "./design";

export const useTagViewStore = defineStore("tagView", () => {
  let visitedViews: Ref<TagView[]> = ref<TagView[]>([]);
  const { push, replace } = useRouter();
  const designStore = useDesignStore();

  /** 添加tag */
  const addView = (view: TagView) => {
    const hasView = visitedViews.value.some((item) => item.path === view.path);
    if (hasView) return;
    visitedViews.value.push(view);
  };

  /** 删除tag */
  const delView = (view: TagView, currentPath: string) => {
    if (view.path === currentPath) return;
    const index = visitedViews.value.findIndex((item) => item.path === view.path);
    if (index === -1) return;
    visitedViews.value.splice(index, 1);
  };

  /** 刷新 */
  const refresh = (view: TagView) => {
    push({ name: "redirect", params: { path: view.path } });
  };

  /** 关闭右侧 */
  const closeRight = (view: TagView) => {
    const index = visitedViews.value.findIndex((item) => item.path === view.path);
    if (index + 1 === visitedViews.value.length) return;
    visitedViews.value.splice(index + 1, 1);
  };

  /** 关闭左侧 */
  const closeLeft = (view: TagView) => {
    const index = visitedViews.value.findIndex((item) => item.path === view.path);
    if (!index) return;
    visitedViews.value.splice(index - 1, 1);
  };

  /** 关闭全部 */
  const closeAll = (view: TagView) => {
    visitedViews.value = visitedViews.value.filter((item) => item.path === view.path);
  };

  /** 点击某个tag的跳转 */
  const toView = (view: TagView, currentPath: string) => {
    if (view.path === currentPath) return;
    push(view.path);
    designStore.setActiveKey(view.name);
  };

  return {
    visitedViews,
    addView,
    delView,
    refresh,
    closeRight,
    closeLeft,
    closeAll,
    toView,
  };
});
